<template>
  <div class="goods_order">
    <div class="order_header">
      <SHeader :title="'生成订单'"></SHeader>

      <div class="address" @click="goToAddress">
        <div class="content">
          <span>{{ address.userName }}</span>
          <span class="phone">{{ address.userPhone }}</span>
          <p>
            {{ address.provinceName }} {{ address.cityName }} {{ address.regionName }}
            {{ address.detailAddress }}
          </p>
        </div>
        <p><van-icon name="arrow" class="icon" /></p>
      </div>
    </div>

    <div class="goods_content">
      <div class="goods_item" v-for="item in cartList" :key="item.goodsId">
        <div class="goods_img">
          <img :src="item.goodsCoverImg" alt="" />
        </div>
        <div class="goods_info">
          <div class="desc">
            <span>{{ item.goodsName }}</span>
            <span>x{{ item.goodsCount }}</span>
          </div>
          <p class="goods_price">￥{{ item.sellingPrice }}</p>
        </div>
      </div>
    </div>

    <div class="pay-wrap">
      <div class="price">
        <span>商品价格</span>
        <span style="color: red">￥{{ totalPrice }}</span>
      </div>
      <van-button @click="handleCreateOrder" type="primary" class="btn" block
        >生成订单</van-button
      >
    </div>

    <van-popup
      closeable
      :close-on-click-overlay="false"
      v-model:show="showPay"
      position="bottom"
      :style="{ height: '30%' }"
      @close="close"
    >
      <div :style="{ width: '90%', margin: '0 auto', padding: '50px 0' }">
        <van-button
          :style="{ marginBottom: '10px' }"
          color="#1989fa"
          block
          @click="handlePayOrder(1)"
          >支付宝支付</van-button
        >
        <van-button color="#4fc08d" block @click="handlePayOrder(2)">微信支付</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
import SHeader from "../components/Header.vue";
import { reactive, toRefs, onMounted, computed } from "vue";
import { Toast } from "vant";
import { useRouter, useRoute } from "vue-router";
import { getLocal, setLocal } from "../common/js/ustil";
import { getByCartItemIds } from "../service/cart";
import { getAddressDetail, getDefaultAddress } from "../service/address";
import { payOrder, createOrder } from "../service/order";

export default {
  components: {
    SHeader,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive({
      cartList: [],
      address: {},
      showPay: false,
      orderNo: "",
      cartItemIds: [],
    });

    const init = async () => {
      Toast.loading({ message: "加载中", forbidClick: true });

      const { cartItemIds, addressId } = route.query;
      let _cartItemIds = [];
      // 保存在本地
      if (cartItemIds) {
        setLocal("cartItemIds", cartItemIds);
        _cartItemIds = JSON.parse(cartItemIds);
      } else {
        _cartItemIds = JSON.parse(getLocal("cartItemIds"));
      }

      const { data } = await getByCartItemIds({
        cartItemIds: _cartItemIds.join(","),
      });
      // 获取收获地址
      const { data: address } = addressId
        ? await getAddressDetail(addressId)
        : await getDefaultAddress();
      if (!address) {
        router.push({ path: "/address" });
        return;
      }
      state.cartList = data;
      state.address = address;
      console.log(address);
      Toast.clear();
    };
    onMounted(() => {
      init();
    });

    const totalPrice = computed(() => {
      let price = state.cartList;
      let sum = 0;
      for (let item of price) {
        sum += item.sellingPrice * item.goodsCount;
      }
      return sum;
    });
    const handleCreateOrder = async () => {
      const params = {
        addressId: state.address.addressId,
        cartItemIds: state.cartList.map((item) => item.cartItemId),
      };
      const { data } = await createOrder(params);
      setLocal("cartItemIds", "");
      state.orderNo = data;
      state.showPay = true;
    };
    const close = () => {
      router.push({ path: "/myOrder" });
    };
    const handlePayOrder = async (type) => {
      await payOrder({ orderNo: state.orderNo, payType: type });
      Toast.success("支付成功");
      setTimeout(() => {
        router.push({ path: "/myOrder" });
      }, 2000);
    };
    const goToAddress = () => {
      router.push({
        path: "/address",
        query: { id: state.address.addressId, from: "/myOrder" },
      });
    };
    return {
      ...toRefs(state),
      totalPrice,
      goToAddress,
      close,
      handleCreateOrder,
      handlePayOrder,
    };
  },
};
</script>

<style lang="less" scoped>
.order_header {
  position: fixed;
  width: 100%;
  z-index: 10000;
  background: #fff;
}

.pay-wrap {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  padding: 10px 0;
  border-top: 1px solid #e9e9e9;
  z-index: 1000;
}
.pay-wrap .btn {
  padding: 0 20px;
}
.pay-wrap .price {
  display: flex;
  justify-content: space-between;
  padding: 15px 10px;
  font-size: 16px;
}
.address {
  display: flex;
  background: #f7f7f8;
  justify-content: space-between;
  padding: 15px;
  align-items: center;
  border-bottom: 2px solid;
  border-image: -webkit-linear-gradient(#87b636, rgb(60, 105, 162), #552db3) 1 10 1; /* 控制边框颜色渐变 */
  border-image: -moz-linear-gradient(#87b636, rgb(60, 105, 162), #552db3) 1 10 1;
  border-image: linear-gradient(#87b636, rgb(60, 105, 162), #552db3) 1 10 1; /* 标准的必须写在最后 */
  .content {
    font-size: 15px;
    .phone {
      margin-left: 20px;
    }
  }
  .icon {
    font-size: 18px;
  }
}

.goods_content {
  padding-top: 180px;
  height: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
}
.goods_item {
  display: flex;
  padding-top: 10px;
  padding-bottom: 10px;

  .goods_img img {
    width: 100%;
    height: 100%;
  }
  .goods_info {
    width: 50%;
    margin-left: 10%;
  }

  .goods_title {
    font-weight: 600;
    font-size: 15px;
    margin: 0;
  }
  .goods_size {
    color: #dcdcdc;
  }
  .desc {
    display: flex;
    justify-content: space-between;
  }
  .goods_price {
    padding-top: 20px;
    font-size: 16px;
    color: red;
  }
}
.goods_item .goods_img {
  width: 25%;
  height: 15vh;
  margin-left: 5%;
}
</style>
